<template>
  <div id="chart-container" class="vo-edit"></div>
</template>
<script>
  import OrgChart from './orgchart'
  import { mergeOptions } from './lodash'
  import { bindEventHandler, getValue } from './utils'
  // 部分可参考orgChart文档
  export default {
    name: 'orgchart',
    props: {
      data: {type: Object, default: null},
      value: {type: Object, required: false, default: null},
      direction: {type: String, default: 't2b'},      // 方向
      verticalDepth: {type: Number},
      toggleSiblingsResp: {type: Boolean, default: false},
      depth: {type: Number, default: 999},
      nodeTitle: {type: String, default: 'objName'},  // title 显示的字段
      parentNodeSymbol: {type: String, default: ''},
      nodeContent: {type: String},
      nodeId: {type: String, default: ''},
      createNode: {type: Function},
      exportButton: {type: Boolean, default: false},
      exportFilename: {type: String},
      chartClass: {type: String, default: ''},
      draggable: {type: Boolean, default: true},
      dropCriteria: {type: Function},
      onDropEnd: {type: Function},
      editNode: {type: Function}
//      beforeAdd: {type: Function}
    },
    data () {
      return {
        orgchart: null,
        defaultOptions: {
          chartContainer: '#chart-container'
        }
      }
    },
    watch: {
      value: function realList () {
        var me = this
        this.$nextTick(function () {
          me.initOrgChart()
        })
      }
    },
    mounted () {
      var me = this
      this.initOrgChart()
      this.$nextTick(function () {
        // 绑定事件
        bindEventHandler('.node', 'drop', me.onDrop, '#chart-container')
        bindEventHandler('.orgchart', 'drop', me.onDrop, '#chart-container')
        bindEventHandler('.org-item-del', 'click', me.triggerInput, '#chart-container')
        bindEventHandler('.item-edit', 'click', me.edit, '#chart-container')
      })
    },
    methods: {
      initOrgChart () {
        const opts = mergeOptions(this.defaultOptions, this.$props)
        this.orgchart = new OrgChart(opts)
      },
      onDrop (e) {
//        if (this.orgchart.chart.error) {
//          this.$root.eventHub.$emit('error', '同一节点只能添加一次')
//          this.orgchart.chart.error = false
//          this.orgchart.chart.isAdd = false
//          return
//        }
        if (this.$props.onDropEnd && this.orgchart.chart.isAdd) {
          this.$props.onDropEnd()
          this.orgchart.chart.isAdd = false
          return
        }
        this.triggerInput()
      },
      // 触发事件，同步数据
      triggerInput () {
        var newList = getValue()
        this.$emit('input', newList)
      },
      edit (e) {
        this.editNode(e.path[2])
      }
    }
  }
</script>
